// 封装购物车模块

import { defineStore } from "pinia";
import { ref, computed } from 'vue'
import { useUserStore } from "./userStore"
import { insertCartAPI, findNewCartListAPI, delCartAPI } from "@/apis/cart"


export const useCartStore = defineStore('cart', () => {
	const userStore = useUserStore();
	// 获取登录状态
	const isLogin = computed(() => userStore.userInfo.token);
	// 1.定义state
	const cartList = ref([]);

	/**
	 * 获取最新购物车列表
	 * @returns {Promise<void>}
	 */
	const updateNewList = async () => {
		const res = await findNewCartListAPI();
		cartList.value = res.result;
	}

	/**
	 * 添加购物车
	 * 已添加过 - count + 1
	 * 没有添加过 - 直接push
	 * 思路：通过匹配传递过来的商品对象中的skuId能不能在cartList中找到
	 * @param goods
	 * @returns {Promise<void>}
	 */
	const addCart = async (goods) => {
		const { skuId, count } = goods
		if (isLogin.value) {
			// 登录之后的加入购物车逻辑
			await insertCartAPI({ skuId, count });
			updateNewList();
		} else {
			const item = cartList.value.find((item) => goods.skuId === item.skuId)
			if (item) {
				// 找到了
				item.count++;
			} else {
				// 没找到
				cartList.value.push(goods)
			}
		}
	}


	/**
	 * 删除购物车
	 * 方法1：找到要删除的下标值 - splice
	 * 方法2：使用数组的过滤方法 - filter
	 * @param skuId
	 */
	const delCart = async (skuId) => {
		if (isLogin.value) {
			// 调用接口实现购物车中的删除功能
			await delCartAPI([skuId])
			updateNewList();
		} else {
			const idx = cartList.value.findIndex((item) => item.skuId === skuId);
			cartList.value.splice(idx, 1);
		}
	}

	/**
	 * 清除购物车
	 */
	const clearCart = () => {
		cartList.value = []
	}

	// 单选功能
	const singleCheck = (skuId, selected) => {
		// 	通过skuId查找到要修改的一项，将他的状态改成selected
		const item = cartList.value.find((item) => item.skuId === skuId);
		item.selected = selected;
	}

	// 全选功能
	const allCheck = (selected) => {
		// 把cartList这的每一项的selected都设置为当前的全选状态
		cartList.value.forEach(item => item.selected = selected)
	}

	// 计算属性
	// 1.商品总数  所有项的count之和
	const allCount = computed(() => cartList.value.reduce((count, item) => count + item.count, 0))
	// 2.商品总价  所有项的count*price之和
	const allPrice = computed(() => cartList.value.reduce((price, item) => price + item.count * item.price, 0))
	// 3.已选择数量
	const selectedCount = computed(() => cartList.value
		.filter(item => item.selected)
		.reduce((count, item) => count + item.count, 0))
	// 4.已选择总价
	const selectedPrice = computed(() => cartList.value
		.filter(item => item.selected)
		.reduce((count, item) => count + item.count * item.price, 0))

	// 是否全选
	const isALL = computed(() => cartList.value.every((item) => item.selected));

	return {
		cartList,
		allCount,
		allPrice,
		isALL,
		selectedCount,
		selectedPrice,
		addCart,
		delCart,
		singleCheck,
		allCheck,
		clearCart,
		updateNewList,
	}
}, {
	persist: true
})
